package mspbots.cw.business.core.workroles;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.cw.business.core.BaseReceiver;
import mspbots.cw.common.ResultMsg;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.Iterator;

/**
 * @author Jay.Yang
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class WorkrolesReceiver extends BaseReceiver {

    private final WorkrolesRepository workrolesRepository;

    @RabbitListener(queues = "connect-wise.workroles.tl")
    public void process(ResultMsg resultMsg) {
        JsonNode entity = resultMsg.getEntity();
        Workroles data = super.objectMapper.convertValue(entity, Workroles.class);
        data.setId(null);
        data.setCwId(resultMsg.getId());
        data.setTenantCode(resultMsg.getTenantId());
        data.setSyncTime(resultMsg.getSyncDate());
        data.setLastUpdated(super.getDateTimeValue(entity.findValue("lastUpdated")));
        if (!ObjectUtils.isEmpty(entity.get("locationIds")) && !entity.get("locationIds").isEmpty()) {
            Iterator<JsonNode> locationIds = entity.get("locationIds").elements();
            String ids = "";
            while (locationIds.hasNext()) {
                ids += locationIds.next().asText() + ",";
            }
            if (!StringUtils.isEmpty(ids)) {
                data.setLocationIdsStr(ids.substring(0, ids.length() - 1));
            }
        }


        this.workrolesRepository.findByCwIdAndTenantCode(resultMsg.getId(), resultMsg.getTenantId())
                .map(result -> {
                    data.setId(result.getId());
                    return data;
                })
                .defaultIfEmpty(data)
                .flatMap(this.workrolesRepository::save).block(Duration.ofSeconds(10));
    }

}
